library flutterptzscontrol;

import 'dart:math';

import 'package:flutter/material.dart';

///点击回调
///-1 超出范围
///1 左
///2 上
///3 右
///4 下
typedef void PtzsCallback(int status);

class PtzsControlWidget extends StatefulWidget {
  ///内径
  final double _rIn;

  ///外径
  final double _r;

  ///点击回调
  final PtzsCallback _callback;

  PtzsControlWidget(this._rIn, this._r, this._callback);

  @override
  State<StatefulWidget> createState() {
    return _PtzsControlWidgetState();
  }
}

class _PtzsControlWidgetState extends State<PtzsControlWidget> {
  int status = 0;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanDown: (details) {
        //坐标系转换
        var x = details.localPosition.dx - widget._r;
        var y = -(details.localPosition.dy - widget._r);

        //判断点击位置是否超出范围
        var dis = Point(x, y).distanceTo(Point(0, 0));

        //超出范围
        if (dis > widget._r || dis < widget._rIn) {
          status = -1;
        } else if (x.abs() >= y.abs()) {
          //右
          if (x >= 0) {
            status = 3;
            //左
          } else {
            status = 1;
          }
        } else {
          //上
          if (y >= 0) {
            status = 2;
            //下
          } else {
            status = 4;
          }
        }
        widget._callback(status);
        setState(() {});
      },
      onPanEnd: (details) {
        status = 0;
        setState(() {});
      },
      child: Stack(
        children: <Widget>[
          Image.asset(
            status == 1
                ? 'images/video_left_selected.png'
                : 'images/video_left.png',
            package: 'flutterptzscontrol',
          ),
          Image.asset(
            status == 2
                ? 'images/video_up_selected.png'
                : 'images/video_up.png',
            package: 'flutterptzscontrol',
          ),
          Image.asset(
            status == 3
                ? 'images/video_right_selected.png'
                : 'images/video_right.png',
            package: 'flutterptzscontrol',
          ),
          Image.asset(
            status == 4
                ? 'images/video_down_selected.png'
                : 'images/video_down.png',
            package: 'flutterptzscontrol',
          ),
        ],
      ),
    );
  }
}
